import React from 'react';
import { NavBar, Icon } from "antd-mobile"
import { connect } from "react-redux"
import { request } from "../../utils/request"

import { actionUpdateCity, actionClearCity } from "../../store/actionCreator"
import { List } from 'react-virtualized';

// 引入局部样式文件
import Css from "./index.module.scss"
class CitySelect extends React.Component {
    state = {
        hotCityList: [],
        allCityList: [],
        letterList: [],
        currentIndex: 0
    }
    constructor() {
        super();
        this.hRef = React.createRef();
    }
    async componentDidMount() {
        console.log('城市', this.props.cityName);
        // this.getCityHot();
        // this.getAllCity();
        let finalList = []
        // 字母列表初始化
        let letterList = ["#", "热"];
        // 优化点：
        //   1，请求是同步执行的，需要等第一个执行完毕才执行第二个，
        //   2，我们需要让他们同时执行，不需要相互等待
        //   解决方法
        //   Promise.all()

        // jsdoc  写代码注释的规范 /** */
        /**
         * @param {String} 字符串型
         * @param {Number}  数值型
         * 
         *  */
        var res = await Promise.all([request.get('/area/hot'), request.get('/area/city?level=1')])
        // 热门城市
        const hots = res[0].data.body;
        finalList.push({ name: '当前定位', children: [{ name: this.props.cityName }] })
        finalList.push({ name: '热门城市', children: hots.map(v => ({ name: v.label })) })
        // 全部城市列表
        const allCityList = res[1].data.body;
        // 第一次排序
        allCityList.sort((a, b) => a.short < b.short ? -1 : 1);

        // 遍历数组进行分类
        allCityList.forEach(v => {
            //获取v.short属性中的第一个字母，并转为大写
            const firstLetter = v.short[0].toUpperCase();
            //遍历数组，判断firstLetter类型是否在allCityList中存在
            const index = finalList.findIndex(vv => vv.name === firstLetter);
            if (index === -1) {
                // 不存在
                finalList.push({ name: firstLetter, children: [{ name: v.label }] });
                letterList.push(firstLetter)
            } else {
                // 存在
                finalList[index].children.push({ name: v.label })
            }
        })

        console.log("finalList")
        console.log(finalList)
        // 更新数据
        this.setState({
            allCityList: finalList,
            letterList
        })

        this.hRef.measureAllRows();
    }
    getAllCity() {
        request.get('/area/city?level=1').then(res => {
            let newArr = res.data.body;
            let emptyArr = [];

            function deepSort(params) {
                //  1.0遍历数组
                let children = [];
                newArr.forEach(v => {
                    if (v.short.slice(0, 1) === params) {
                        children.push({ name: v.label });
                    }
                });
                //最后遍历完了之后，将数据push进去
                if (children.length > 0) {
                    emptyArr.push({ name: params.toUpperCase(), children })
                }
                //数组置为空
                children = [];

            }
            // 第一步排序
            newArr.sort((a, b) => {
                //排序规则
                return a.short < b.short ? -1 : 1;

            })
            let zimuList = ["a", "b", "c", "d",
                "e",
                "f",
                "g",
                "h",
                "i",
                "j",
                "k",
                "l",
                "m",
                "n",
                "o",
                "p",
                "q",
                "r",
                "s",
                "t",
                "u",
                "v",
                "w",
                "x",
                "y",
                "z"]
            // deepSort("a");
            // deepSort("b");
            zimuList.forEach(v => {
                deepSort(v);
            })
            // console.log('新的数组')
            // console.log(newArr)
            console.log('emptyArr')
            console.log(emptyArr);

            // 更新数据
            this.setState({
                allCityList: emptyArr
            })
        })
    }
    // 字母列表点击
    handleClick = (i) => {
        this.setState({ currentIndex: i })
        this.hRef.scrollToRow(i);
    }
    //城市点击跳转，修改redux中的城市名称
    handleCityItemClick = (cityname) => {
        // 第一种方法：先清除redux中旧的城市数据
        // this.props.handleClearCity();
        // 第二种方法：异步Promise
        this.props.handleUpdateCity(cityname).then(() => {
            //城市名称已经拿到再返回上一页
            this.props.history.goBack();
        });
        // console.dir(res);  //结果是promise，是个异步
        // 返回上一页

    }
    //城市列表的渲染函数
    rowRenderer = ({ key, index, isScrolling, isVisible, style, }) => {
        const group = this.state.allCityList[index];
        return (
            <div key={key} style={style}>
                <div className={Css.title}>{group.name}</div>
                <div className={Css.item}>
                    {group.children.map(v => <div className={Css.cityname} key={v.name}
                        onClick={() => this.handleCityItemClick(v.name)}>{v.name}</div>)}
                </div>
            </div>
        )
    }
    //每一大行高度的计算函数
    rowHeight = ({ index }) => {
        // const rate = 10 * parseFloat(document.documentElement.style.fontSize) / 375;
        return this.state.allCityList[index].children.length * 50 + 40;
    }
    // 行滚动完毕事件
    onRowsRendered = ({ startIndex }) => {
        if (this.state.currentIndex === startIndex) return;
        // console.log(startIndex)
        this.setState({ currentIndex: startIndex });
    }
    render() {
        const { allCityList, letterList, currentIndex } = this.state;

        return (
            <div className={Css.city_select}>
                {/* 顶部导航栏开始 */}
                <NavBar
                    mode="light"
                    icon={<Icon type="left" />}
                    onLeftClick={() => this.props.history.goBack()}
                >城市选择</NavBar>
                {/* 顶部导航栏结束 */}
                {/* 城市列表 开始 */}
                <div className={Css.city_select_content}>
                    <div className={Css.city_main}>
                        <List
                            width={window.screen.width}
                            height={window.screen.height - 45}
                            rowCount={allCityList.length}
                            rowHeight={this.rowHeight}
                            rowRenderer={this.rowRenderer}
                            // 滚动到索引
                            // scrollToIndex={currentIndex}  解决左边城市列表和右边字母列表的滑动bug
                            //设置列表索引的对齐位置 start center end
                            scrollToAlignment="start"
                            // 赋值ref
                            ref={(ref) => this.hRef = ref}
                            // 行渲染完毕事件（参数-滚动到的索引）
                            onRowsRendered={this.onRowsRendered}
                        />

                    </div>
                    {/* 城市列表 结束 */}
                    {/* 字母列表开始 */}
                    <div className={Css.letter_view}>
                        {letterList.map((v, i) =>
                            <div onClick={() => this.handleClick(i)} className={[Css.letter_item, i === currentIndex ? Css.active : ''].join(' ')} key={v}>
                                <span>{v}</span>
                            </div>
                        )}
                    </div>
                    {/* 字母列表结束 */}
                </div>
            </div>
        );
    }
}
const mapStateToProps = (state) => ({
    cityName: state.CityReducer.cityname.name
})
const mapDispatchToProps = (dispatch) => {
    return {
        handleUpdateCity(cityName) {
            return dispatch(actionUpdateCity(cityName))

        },
        // 清除旧的城市名称
        handleClearCity() {
            dispatch(actionClearCity())
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(CitySelect);